/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package treearray;

/**
 *
 * @author leonardo
 */
public class Arvores {

    private int[] data;
    private int heapTamanho;

    public Arvores(int size) {
        data = new int[size];
        heapTamanho = 0;
    }

    private int getIndiceFilhoEsquerda(int nodeIndex) {
        return 2 * nodeIndex + 1;
    }

    private int getIndiceFilhoDireita(int nodeIndex) {
        return 2 * nodeIndex + 2;
    }

    private int getIndicePai(int nodeIndex) {
        return (nodeIndex - 1) / 2;
    }

    public void inserir(int value) {
        if (heapTamanho == data.length) {
            System.out.println("Erro Heap Overflow");
        } else {

            data[heapTamanho++] = value;
            heapifyUp(heapTamanho - 1);
        }
    }

        

    private void heapifyUp(int childInd) {
        int tmp = data[childInd];
        while (childInd > 0 && tmp < data[getIndicePai(childInd)]) {
            data[childInd] = data[ getIndicePai(childInd)];
            childInd = getIndicePai(childInd);
        }
        data[childInd] = tmp;
    }

    public static void main(String[] args) {

        int vetor[] = {2, 7, 5, 2, 6, 9, 5, 11, 4};

        Arvores tree = new Arvores(9);
        for (int i = 0; i < vetor.length; i++) {
            tree.inserir(vetor[i]);
        }

        for (int i = 0; i < tree.data.length; i++) {
            System.out.print(" " + tree.data[i]);
        }

    }

}
